package com.gjj.controller;

import com.gjj.common.PropertiesUtils;
import com.gjj.model.MyUpload;
import com.gjj.utils.DocToHtmlUtils;
import com.jfinal.core.Controller;
import com.jfinal.upload.UploadFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.*;

import static com.gjj.utils.Test.docToHtml;

public class IndexController extends Controller {

    private Logger logger = LoggerFactory.getLogger(IndexController.class);

    public void index(){
        render("index.html");
    }


    //上传文件
    public void upload(){
        UploadFile file = getFile("filename");
        if (file == null) {
            logger.info("上传失败");
        }else{
            boolean inserted = new MyUpload().set("file_path", file.getFileName()).save();

            if (inserted) {
                logger.info("上传成功");
            }else{
                logger.info("上传失败");
            }
        }
        renderNull();

    }



    public void showUploadFiles() throws Exception {
        String file_server_host=PropertiesUtils.getProperty("file_server_host");
        String upload_dir = PropertiesUtils.getProperty("upload_dir");

        Map<String, Object> datas = new HashMap<>();
        List<String> pathList = new ArrayList<>();
        List<MyUpload> myUploads = MyUpload.dao.find("select * from uploadfile");
        for (MyUpload myUpload : myUploads) {
            String file_path = myUpload.getStr("file_path");
            pathList.add(file_path);
        }
        datas.put("data",myUploads);
        datas.put("url",file_server_host+upload_dir);
        renderJson(datas);

    }


    public void showDoc() throws Exception {
        String filename=getPara("filename");
//        String test=URLDecoder.decode(filename, "UTF-8");
        String sourceFileName = PropertiesUtils.getProperty("sourceFileName");
        String targetFileName = PropertiesUtils.getProperty("targetFileName");
        String imagePathStr = PropertiesUtils.getProperty("imagePathStr");
        String file_server_host=PropertiesUtils.getProperty("file_server_host");
        String file=filename.substring(0,filename.indexOf('.'));
        file= URLDecoder.decode(file, "UTF-8");

        String generateFilename=System.currentTimeMillis()+new Random().nextInt(100)+"";

        String file_type = filename.substring(filename.lastIndexOf('.') + 1, filename.length());

        if(file_type.equals("doc")){
            DocToHtmlUtils.docToHtml(sourceFileName+file+".doc",targetFileName+generateFilename+".html",imagePathStr);
        }else if(file_type.equals("docx")){
            DocToHtmlUtils.docxToHtml(sourceFileName+file+".docx",targetFileName+generateFilename+".html",imagePathStr);

        }



        redirect(file_server_host+"/doc/"+generateFilename+".html");
    }


}
